import axios from "axios"
const cartModule = {
    namespaced: true,
    state() {
        return {
            goodsList: []
        }
    },
    mutations: {
        setGoodsList(state, newList) {
            state.goodsList = newList
        },
        setGoodsItemState(state, obj) {
            state.goodsList[obj.index].goods_state = obj.checked
        },
        setGoodsListState(state, checked) {
            state.goodsList.forEach(obj => obj.goods_state = checked)
        },
        jiajiajiajia(state,index){
            return state.goodsList[index].goods_count++
        },
        jianjianjianjian(state,index){
            return state.goodsList[index].goods_count--
        }
    },
    actions: {
        async asyncSetGoodsList(store) {
            const resp = await axios({
                method: 'GET',
                url: 'https://www.escook.cn/api/cart'
            })

            store.commit('setGoodsList', resp.data.list)
        }
    },
    getters: {
        totalCount(state) {
            return state.goodsList.reduce((sum, obj) => {
                if (obj.goods_state) {
                    sum += obj.goods_count
                }
                return sum
            }, 0)
        },
        totalPrice(state) {
            return state.goodsList.reduce((sum, obj) => {
                if (obj.goods_state) {
                    sum += obj.goods_count * obj.goods_price
                }
                return sum
            }, 0)
        },

        isAllChecked(state) {
            return state.goodsList.every(obj => obj.goods_state)

        }
    },

}

export default cartModule